package com.blb.eduuserservice.controller;

import com.blb.common.entity.User;
import com.blb.common.util.JwtUtils;
import com.blb.common.util.ResponseResult;
import com.blb.common.util.RsaUtils;
import com.blb.eduuserservice.config.WXConfigurationProperties;
import com.blb.eduuserservice.service.WxLoginService;
import com.blb.eduuserservice.util.UserTokenUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/api/ucenter/wx")
@Controller
public class WXController {

    @Autowired
    private WxLoginService wxLoginService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private WXConfigurationProperties wxConfig;

    @RequestMapping("callback")
    public String wxCallback(String code) throws JsonProcessingException {
        User user = wxLoginService.wxLogin(code);
        log.info("user:{}",user);
        ResponseResult<User> result = UserTokenUtils.generateUserToken(user,redisTemplate);
        String json = new ObjectMapper().writeValueAsString(result);
        return "redirect:"+ wxConfig.getWebCallbackURL() + json;
    }

    @ResponseBody
    @RequestMapping("getWxParam")
    public ResponseResult<Map> getWxParam(){
        Map<String,String> params = new HashMap<>();
        params.put("appid", wxConfig.getAppId());
        params.put("redirectUri", wxConfig.getRedirectURL());
        params.put("scope", "snsapi_login");
        params.put("state", System.currentTimeMillis()+"");
        return ResponseResult.ok(params);
    }
}
